package com.qny.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qny.ai.common.JwtUtil;
import com.qny.ai.common.PasswordUtil;
import com.qny.ai.common.ErrorCode;
import com.qny.ai.dto.user.UserLoginRequest;
import com.qny.ai.dto.user.UserRegisterRequest;
import com.qny.ai.entity.AppUser;
import com.qny.ai.exception.BusinessException;
import com.qny.ai.mapper.AppUserMapper;
import com.qny.ai.service.UserService;
import com.qny.ai.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final AppUserMapper appUserMapper;

    @Override
    public Long register(UserRegisterRequest request) {
        // 简单唯一性校验
        Long exists = appUserMapper.selectCount(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getUsername, request.getUsername()));
        if (exists != null && exists > 0) {
            throw new BusinessException(ErrorCode.CONFLICT.getCode(), "用户名已存在");
        }
        AppUser user = AppUser.builder()
                .username(request.getUsername())
                .password(PasswordUtil.encode(request.getPassword()))
                .email(StringUtils.hasText(request.getEmail()) ? request.getEmail() : null)
                .preferredLanguage("zh")
                .build();
        int inserted = appUserMapper.insert(user);
        if (inserted != 1) {
            throw new BusinessException(ErrorCode.SERVER_ERROR.getCode(), "注册失败");
        }
        return user.getId();
    }

    @Override
    public UserVO login(UserLoginRequest request) {
        AppUser user = appUserMapper.selectOne(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getUsername, request.getUsername()));
        if (user == null) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED.getCode(), "用户名或密码错误");
        }
        
        // 验证密码
        if (!PasswordUtil.matches(request.getPassword(), user.getPassword())) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED.getCode(), "用户名或密码错误");
        }
        
        String token = JwtUtil.generateToken(String.valueOf(user.getId()), java.util.Map.of(
                "username", user.getUsername()
        ), null, null);
        return UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .avatarUrl(user.getAvatarUrl())
                .preferredLanguage(user.getPreferredLanguage())
                .token(token)
                .build();
    }
    
    @Override
    public UserVO updateProfile(Long userId, String username, String email) {
        AppUser user = appUserMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND.getCode(), "用户不存在");
        }
        
        // 检查用户名是否被其他用户使用
        if (StringUtils.hasText(username) && !username.equals(user.getUsername())) {
            Long exists = appUserMapper.selectCount(new LambdaQueryWrapper<AppUser>()
                    .eq(AppUser::getUsername, username)
                    .ne(AppUser::getId, userId));
            if (exists != null && exists > 0) {
                throw new BusinessException(ErrorCode.CONFLICT.getCode(), "用户名已存在");
            }
        }
        
        if (StringUtils.hasText(username)) {
            user.setUsername(username);
        }
        if (StringUtils.hasText(email)) {
            user.setEmail(email);
        }
        
        appUserMapper.updateById(user);
        
        return UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .avatarUrl(user.getAvatarUrl())
                .preferredLanguage(user.getPreferredLanguage())
                .build();
    }
    
    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        AppUser user = appUserMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND.getCode(), "用户不存在");
        }
        
        // 验证旧密码
        if (!PasswordUtil.matches(oldPassword, user.getPassword())) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED.getCode(), "原密码错误");
        }
        
        // 更新密码
        user.setPassword(PasswordUtil.encode(newPassword));
        appUserMapper.updateById(user);
        
        return true;
    }
    
    @Override
    public UserVO getCurrentUser(Long userId) {
        AppUser user = appUserMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND.getCode(), "用户不存在");
        }
        
        return UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .avatarUrl(user.getAvatarUrl())
                .preferredLanguage(user.getPreferredLanguage())
                .build();
    }
}


